package org.com.lcuiot.service;

import org.com.lcuiot.common.LcuConst;
import org.com.lcuiot.common.TimeUtil;
import org.com.lcuiot.database.dto.Result;
import org.com.lcuiot.database.entity.Device;

import org.com.lcuiot.database.entity.Product;
import org.com.lcuiot.database.entity.SendCommand;
import org.com.lcuiot.database.mapper.DeviceMapper;

import org.com.lcuiot.database.mapper.ProductMapper;
import org.com.lcuiot.onenet.api.SendCmdsApi;
import org.com.lcuiot.onenet.response.BasicResponse;
import org.com.lcuiot.onenet.response.NewCmdsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Optional;

/**
 * 设备服务
 *
 * @author gaoge
 * @since 2022/10/27 14:31
 */
@Service
public class DeviceService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceService.class);
    private final DeviceMapper deviceMapper;
    private final ProductMapper productMapper;

    @Autowired
    public DeviceService(DeviceMapper deviceMapper, ProductMapper productMapper) {
        this.deviceMapper = deviceMapper;
        this.productMapper = productMapper;
    }


    public List<Device> selectByDeviceId(String deviceId) {
        Device device = new Device();
        device.setDevId(deviceId);
        return deviceMapper.selectList(device);
    }

    /**
     * 根据设备ID修改设备信息
     *
     * @param s 请求信息
     * @return Result<Object>
     */
    public Result<Object> patchDevice(Device s) {
        Result<Object> result = Result.build();
        try {
            Optional<Device> device = deviceMapper.selectByPrimaryKey(s.getDevId());
            if (device.isPresent()) {
                s.setUpdateAt(TimeUtil.currentTimeMillis());
                deviceMapper.updateByPrimaryKeySelective(s);
            }
            result.setData(s);
        } catch (Exception e) {
            logger.error("根据设备ID修改设备信息发生异常:", e);
            result.setCode(500).setMsg("根据设备ID修改设备信息发生异常");
        }
        return result;
    }

    public List<Device> selectAll() {
        Device device = new Device();
        return deviceMapper.selectList(device);
    }

    public Optional<Device> selectByDeviceNameAndProductId(String devName, String productId) {
        Device device = new Device();
        device.setDevName(devName);
        device.setProductId(productId);
        return deviceMapper.selectOne(device);
    }

    public List<Device> selectByProductId(String productId) {
        Device device = new Device();
        device.setProductId(productId);
        return deviceMapper.selectList(device);
    }

    /**
     * 向设备发送命令
     *
     * @param s 请求信息
     * @return Result<Object>
     */
    public Result<Object> sendCommand(SendCommand s) {
        Result<Object> result = Result.build();
        try {

            Optional<Device> deviceOptional = deviceMapper.selectByPrimaryKey(s.getDevId());
            if (!deviceOptional.isPresent()) {
                return result.setCode(500).setMsg("设备数据流不存在");
            }
            Optional<Product> product = productMapper.selectByPrimaryKey(s.getProductId());
            if (!product.isPresent()) {
                return result.setCode(500).setMsg("产品信息不存在");
            }
            SendCmdsApi sendCmdsApi = new SendCmdsApi(s.getDevId(), null, null, null, s.getContents(), product.get().getMasterKey());
            BasicResponse<NewCmdsResponse> newCmdsResponseBasicResponse = sendCmdsApi.executeApi();
            if (newCmdsResponseBasicResponse.errno == 0 && newCmdsResponseBasicResponse.getError().equals(LcuConst.SUCC)) {
                result.setData(newCmdsResponseBasicResponse);
            } else {
                result.setCode(500).setMsg(newCmdsResponseBasicResponse.getError() + ":" + newCmdsResponseBasicResponse.getErrno());
            }
        } catch (Exception e) {
            logger.error("设备下发命令发生异常:", e);
            result.setCode(500).setMsg("设备下发命令发生异常");
        }
        return result;
    }
}
